package question.solution48;

import question.SolutionTemplate;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution48 implements SolutionTemplate {

    public void rotate(int[][] matrix) {
        int matrixSize = matrix.length;
        float centerX = ((float)matrixSize-1)/2;
        for(int i=0;i<centerX;i++){
            for (int j = i; j < matrixSize - 1 - i; j++) {
                swap4(matrix, centerX, i, j);
            }
        }
    }

    private void swap4(int[][] matrix, float center, int coordinateX, int coordinateY){
        int nextX = coordinateY;
        int nextY = (int)(center - coordinateX + center);
        int elementToput = matrix[nextX][nextY];
        matrix[nextX][nextY] = matrix[coordinateX][coordinateY];

        coordinateX = nextX;
        coordinateY = nextY;
        nextX = coordinateY;
        nextY = (int)(center - coordinateX + center);
        int temp = matrix[nextX][nextY];
        matrix[nextX][nextY] = elementToput;
        elementToput = temp;

        coordinateX = nextX;
        coordinateY = nextY;
        nextX = coordinateY;
        nextY = (int)(center - coordinateX + center);
        temp = matrix[nextX][nextY];
        matrix[nextX][nextY] = elementToput;
        elementToput = temp;

        coordinateX = nextX;
        coordinateY = nextY;
        nextX = coordinateY;
        nextY = (int)(center - coordinateX + center);
        matrix[nextX][nextY] = elementToput;

    }

    private int[][] getMatrixByString(String matrixString){
        String[] lines = matrixString.split("],\\[");
        for(int i=0;i<lines.length;i++){
            String newLine = lines[i].replace("[","");
            lines[i] = newLine;
            newLine = lines[i].replace("]","");
            lines[i] = newLine;
        }
        int[][] result = new int[lines.length][];
        for(int j=0;j<lines.length;j++){
            String line = lines[j];
            String[] numberStrings = line.split(",");
            int[] lineResult = new int[numberStrings.length];
            for (int i = 0; i < numberStrings.length; i++) {
                lineResult[i] = Integer.valueOf(numberStrings[i]);
            }
            result[j] = lineResult;
        }
        return result;
    }

    public void test() {

        int[][] numMatrix = getMatrixByString("[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]");
        rotate(numMatrix);
        return;
    }
}
